package com.whf.android.jar.tool;

import android.content.pm.PackageManager;
import android.content.pm.Signature;

import androidx.annotation.Nullable;

import com.whf.android.jar.app.Latte;
import com.whf.android.jar.util.log.LatteLogger;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 实现签名证书的校验
 *
 * @author qf
 * @version 1.0.3
 */
public class CertificateUtils {



    /**
     * 校验签名证书是否匹配
     *
     * @param signatureSHA1 签名SHA1值
     * @return 如果签名证书匹配则返回true，否则返回false
     */
    public static boolean verifySignature(String signatureSHA1) {
        try {
            // 获取应用的签名SHA1值
            String appSignatureSHA1 = getAppSignatureSHA1();
            if (appSignatureSHA1 == null) {
                LatteLogger.e("无法获取应用的签名SHA1值");
                return false;
            }
            // 比较签名SHA1值是否匹配
            return appSignatureSHA1.equals(signatureSHA1);
        } catch (NoSuchAlgorithmException e) {
            LatteLogger.e("无法获取SHA1算法" + e.getMessage());
            return false;
        }
    }

    /**
     * 获取应用的签名SHA1值
     *
     * @return 应用的签名SHA1值，如果获取失败则返回null
     * @throws NoSuchAlgorithmException 如果无法获取SHA1算法则抛出异常
     */
    @Nullable
    private static String getAppSignatureSHA1() throws NoSuchAlgorithmException {
        PackageManager packageManager = Latte.getApplicationContext().getPackageManager();
        // 获取应用的签名信息
        Signature[] signatures = packageManager.getPackageArchiveInfo(Latte.getApplicationContext().getPackageResourcePath(), 0).signatures;
        // 获取签名SHA1值并返回第一个匹配的结果（如果有多个签名的话）
        for (Signature signature : signatures) {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.update(signature.toByteArray());
            byte[] digest = messageDigest.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            if (sb.toString().equals(Latte.getApplicationContext().getPackageName())) {
                return sb.toString();
            }
        }
        return null; // 没有找到匹配的签名SHA1值
    }
}